package com.usefullc.system.service;

import com.usefullc.system.query.BaseQuery;
import com.usefullc.system.dao.SerialNumberDao;
import com.usefullc.system.domain.SerialNumber;
import com.usefullc.system.query.SerialNumberQuery;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Sampson
 * @date: 2022-04-16 17:15
 */
@Service
public class SerialNumberService extends AbstractBizService<SerialNumber,SerialNumberQuery> {

    @Autowired
    private SerialNumberDao serialNumberDao;

    @Override
    public List<Predicate> getPredicates(Root<SerialNumber> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder, SerialNumberQuery q) {
        SerialNumberQuery thisQuery = (SerialNumberQuery) q;
        List<Predicate> predicates = new ArrayList<>();
        if (thisQuery.getDelState() != null) {
            predicates.add(criteriaBuilder.equal(root.get("delState"), thisQuery.getDelState()));
        }
        if (StringUtils.isNotEmpty(thisQuery.getTableName())) {
            predicates.add(criteriaBuilder.equal(root.get("tableName"), thisQuery.getTableName()));
        }
        if (StringUtils.isNotEmpty(thisQuery.getType())) {
            predicates.add(criteriaBuilder.equal(root.get("type"), thisQuery.getType()));
        }
        if (thisQuery.getNo() != null) {
            predicates.add(criteriaBuilder.equal(root.get("no"), thisQuery.getNo()));
        }
        return predicates;
    }

    @Transactional
    public String getSerialNumber(String tableName, String type) {
        SerialNumberQuery query = new SerialNumberQuery();
        query.setTableName(tableName);
        query.setType(type);
        Integer newNo = 1;
        SerialNumber serialNumber = this.findOne(query);
        if (serialNumber == null) {
            serialNumber = new SerialNumber();
            serialNumber.setTableName(tableName);
            serialNumber.setType(type);
            serialNumber.setNo(newNo);
            try {
                this.save(serialNumber);
            } catch (Exception e) {
                //约束异常，重新获取
                return getSerialNumber(tableName, type);
            }
        } else {
            serialNumberDao.incrNo(serialNumber.getId());
            newNo = serialNumber.getNo() + 1;
        }
        String parent = "";
        if (!type.equalsIgnoreCase("0")) {
            parent = type;
        }
        String resultNo = parent + StringUtils.leftPad(newNo.toString(), 4, '0');
        return resultNo;

    }
}
